package com.ruoyi.web.controller.revenue;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.WaterBill;
import com.ruoyi.system.domain.WaterMonthlyUsage;
import com.ruoyi.system.service.IWaterBillService;
import com.ruoyi.system.service.IWaterMonthlyUsageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 水费账单Controller
 *
 * @author ruoyi
 * @date 2025-09-23
 */
@RestController
@RequestMapping("/revenue/bill")
public class WaterBillController extends BaseController
{
    @Autowired
    private IWaterBillService waterBillService;

    @Autowired
    private IWaterMonthlyUsageService waterMonthlyUsageService;

    /**
     * 查询水费账单列表
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:list')")
    @GetMapping("/list")
    public TableDataInfo list(WaterBill waterBill)
    {
        startPage();
        List<WaterBill> list = waterBillService.selectWaterBillList(waterBill);
        return getDataTable(list);
    }

    /**
     * 查询月用水量汇总统计
     */
    @GetMapping("/monthStatistics")
    public AjaxResult monthStatistics()
    {
        /*Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String lastMonth = sdf.format(calendar.getTime());*/
        WaterBill waterBill = new WaterBill();
//        waterBill.setMonth(lastMonth);
        List<WaterBill> list = waterBillService.selectWaterBillList(waterBill);
        // 如果需要按月份自然排序
        Map<String, Double> monthlyUsageMap = list.stream()
                .collect(Collectors.groupingBy(
                        WaterBill::getMonth,
                        TreeMap::new,  // 使用TreeMap实现自动排序
                        Collectors.summingDouble(WaterBill::getUsageAmount)
                ));
        Double lastMonthUsage = StringUtils.getLastEntry(monthlyUsageMap).getValue();
        BigDecimal bd = new BigDecimal(lastMonthUsage/31);
        Map map = new HashMap();
        map.put("lastMonthUsage",lastMonthUsage); // 上月用水量
        map.put("avgDailyUsage",bd.setScale(2, RoundingMode.HALF_UP));  // 平均日用水量
        Optional<Map.Entry<String, Double>> maxEntry = monthlyUsageMap.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue()); // 获取最大用水量
        map.put("peakDate",maxEntry.get().getKey()); // 峰用水日期
        map.put("peakUsage",maxEntry.get().getValue()); // 峰用水量
        map.put("monthMap",monthlyUsageMap); // 月用水量
        return success(map);
    }

    /**
     * 导出水费账单列表
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:export')")
    @Log(title = "水费账单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WaterBill waterBill)
    {
        List<WaterBill> list = waterBillService.selectWaterBillList(waterBill);
        ExcelUtil<WaterBill> util = new ExcelUtil<WaterBill>(WaterBill.class);
        util.exportExcel(response, list, "水费账单数据");
    }

    /**
     * 获取水费账单详细信息
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(waterBillService.selectWaterBillById(id));
    }

    /**
     * 新增水费账单
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:add')")
    @Log(title = "水费账单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WaterBill waterBill)
    {
        String billNumber = waterBill.getBillNumber();
        if (StringUtils.isEmpty(billNumber)){
            waterBill.setBillNumber(waterBillService.getBillNumber());
        }
        addMonthlyUsage(waterBill); // 添加月用水量
        return toAjax(waterBillService.insertWaterBill(waterBill));
    }

    private int addMonthlyUsage(WaterBill waterBill) {
        WaterMonthlyUsage waterMonthlyUsage = new WaterMonthlyUsage();
        waterMonthlyUsage.setMeterNo(waterBill.getMeterNo());
        waterMonthlyUsage.setUserId(waterBill.getUserId());
        waterMonthlyUsage.setUserName(waterBill.getUserName());
        waterMonthlyUsage.setMonth(waterBill.getMonth());
        waterMonthlyUsage.setLastReading(waterBill.getMeterReadLast());
        waterMonthlyUsage.setCurrentReading(waterBill.getMeterReadNow());
        waterMonthlyUsage.setMonthlyConsumption(waterBill.getUsageAmount());
        return waterMonthlyUsageService.insertWaterMonthlyUsage(waterMonthlyUsage);
    }

    /**
     * 修改水费账单
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:edit')")
    @Log(title = "水费账单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WaterBill waterBill)
    {
        return toAjax(waterBillService.updateWaterBill(waterBill));
    }

    /**
     * 删除水费账单
     */
    @PreAuthorize("@ss.hasPermi('revenue:bill:remove')")
    @Log(title = "水费账单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(waterBillService.deleteWaterBillByIds(ids));
    }
}
